package cn.itcast.demo;

import cn.itcast.bean.Student;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/addStudentServlet")
public class addStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//            获取学生信息
//        Map<String, String[]> map = req.getParameterMap();
//        Student student = new Student();
//        try {
//            BeanUtils.populate(student,map);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
        resp.setContentType("text/html;charset=UTF-8");
        String username = req.getParameter("username");
        String age = req.getParameter("age");
        String score = req.getParameter("score");
        Student student = new Student();
        student.setUsername(username);
        student.setAge(Integer.parseInt(age));
        student.setScore(Integer.parseInt(score));

//        接收数据 把数据写入文档、
        BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\student.txt",true));
        bw.write(student.getUsername() + "," + student.getAge() + "," + student.getScore());
        bw.newLine();
        bw.close();
        resp.getWriter().write("保存成功");
//        跳转到首页
        System.out.println();
        resp.setHeader("Refresh","3;/stu/index.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
